// TcpHanlde
package main

import "github.com/miekg/dns"

type ServerHandler struct{}

func (s *ServerHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {

	L("Receive question:%s from %s(%s)", r.Question[0].Name, w.RemoteAddr().String(), w.RemoteAddr().Network())
	var renderMsg *dns.Msg
	ip := myHosts.getSelfIp(r.Question[0].Name)
	if ip != "" {
		renderMsg = r.Copy()
		rr, _ := dns.NewRR(r.Question[0].Name + " 299 IN A " + ip)
		renderMsg.Answer = append(renderMsg.Answer, rr)
		L("%s", "get "+r.Question[0].Name+" ip "+ip+" from tadns")

		w.WriteMsg(renderMsg)
	} else {
		c := new(dns.Client)
		rs, _, err := c.Exchange(r, settings.RemoteDns+":53")
		if err != nil {
			L("get %s err:%s", r.Question[0].Name, err.Error())
			w.Close()
		} else {
			renderMsg = rs.Copy()
			L("%s", "get "+r.Question[0].Name+" ip from "+settings.RemoteDns)

			w.WriteMsg(renderMsg)
		}
	}

}
